package com.erp.controller.advice;

import com.alibaba.fastjson.JSONObject;
import com.erp.entity.result.Result;
import com.erp.entity.result.ResultStatus;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {
    
    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
    
    @ExceptionHandler({AuthorizationException.class, UnauthorizedException.class})
    public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
         logger.error("服务器发生异常" + e.getMessage());
         response.setContentType("application/plain;charset=utf-8");
         PrintWriter writer = response.getWriter();
         writer.write(JSONObject.toJSONString(new Result(ResultStatus.NO_PERMISSION, "权限不足")));
    }
}
